package com.forusers.escrevecheque.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Escrevecheque implements EntryPoint {
	CardinalNumber cardinalNumber = new CardinalNumber();
	String strAnswer;
	final Button checkChequeButton = new Button("Verificar");
	final Button newChequeButton = new Button("Novo");
	final DialogBox dialogBox = new DialogBox();
	final Button closeButton = new Button("Fechar");
	final TextArea answerField = new TextArea();
	
	/**
	 * Setup the buttons, once.
	 */
	public void onModuleLoad() {
		final Label chequeValueField = new Label();
		strAnswer = newCheckValue(chequeValueField);

		checkChequeButton.addStyleName("buttonStyle");
		newChequeButton.addStyleName("buttonStyle");
		newChequeButton.setVisible(false);
		
		answerField.setSize("400px", "50px");
		answerField.setStyleName("tryEditContainer");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("answerValueContainer").add(chequeValueField);
		RootPanel.get("tryEditContainer").add(answerField);
		RootPanel.get("tryButtonContainer").add(checkChequeButton);
		RootPanel.get("newChequeButtonContainer").add(newChequeButton);

		// Focus the cursor on the name field when the app loads
		answerField.setFocus(true);
		answerField.selectAll();

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				showHideNewCheckButton(true);
				dialogBox.hide();
			}
		});

		newChequeButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				newChequeButton.setEnabled(false);
				strAnswer = newCheckValue(chequeValueField);
				showHideNewCheckButton(false);
				checkChequeButton.setEnabled(true);
			}
		});
		
		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				checkCheque();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					checkCheque();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void checkCheque() {
				checkChequeButton.setEnabled(false);
				final String userAnswer = answerField.getValue();
				if (isCloseEnough(strAnswer, userAnswer)) {
					showHideNewCheckButton(true);
				} else {
					showAnswerDialog(strAnswer, userAnswer);
					showHideNewCheckButton(false);
				}
			}

			private boolean isCloseEnough(String strAnswer, String userAnswer) {
				userAnswer = userAnswer.replace(".", "");
				userAnswer = userAnswer.toLowerCase();
				if (strAnswer.toLowerCase().equals(userAnswer)) {
					return true;
				}
				return false;
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		checkChequeButton.addClickHandler(handler);
		answerField.addKeyUpHandler(handler);
	}
	
	private void showHideNewCheckButton(boolean show) {
		newChequeButton.setVisible(show);
		newChequeButton.setFocus(show);
		newChequeButton.setEnabled(show);
		checkChequeButton.setVisible(!show);
		checkChequeButton.setEnabled(!show);
	}
	
	private void showAnswerDialog(final String strCorrectAnswer, final String userAnswer) {
		dialogBox.setText("Resultado");
		dialogBox.setAnimationEnabled(true);
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		HighlightDiff diff = new HighlightDiff(strCorrectAnswer, userAnswer);
		dialogVPanel.add(new HTML("Resposta correto: " + diff.getMarkedUpAnswer()));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);
		dialogBox.show();
	}
	
	private String newCheckValue(final Label chequeValueField) {
		int realValue = Random.nextInt(1234) + 1;
		int centavoValue = 0;
		if (Random.nextBoolean()) {
			centavoValue = Random.nextInt(100);
		}
		
		StringBuffer strAnswerBuf = new StringBuffer();
		strAnswerBuf.append(cardinalNumber.getNumberOnly(realValue, true));
		if (realValue == 1) {
			strAnswerBuf.append(" real");
		} else {
			strAnswerBuf.append(" reais");
		}
		if (centavoValue > 0) {
			strAnswerBuf.append(" e ");
			String strNum = cardinalNumber.getNumberOnly(centavoValue, true);
			strAnswerBuf.append(strNum);
			strAnswerBuf.append(" centavo");
			if (centavoValue != 1) {
				strAnswerBuf.append("s");
			}
		}
		StringBuffer strChequeValue = new StringBuffer();
		strChequeValue.append("" + realValue);
		if (centavoValue < 10) {
			strChequeValue.append(".0");
		} else {
			strChequeValue.append(".");
		}
		strChequeValue.append("" + centavoValue);
		chequeValueField.setText("\u2014R$" + strChequeValue.toString() + "\u2014");
		answerField.setText("");
		
		return strAnswerBuf.toString();
	}
}
